package core.utils;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;

public class LocatorUriChecker {

	private LocatorUriChecker() {

	}

	public static Boolean checkIfLocatorUriIsOpen(String ip, String port) {
		if (checkIfIpIsLocal(ip)) {
			if (checkIfPortIsOpen(Integer.parseInt(port))) {
				return true;
			} else {
				return false;
			}
		} else
			return false;
	}

	private static Boolean checkIfPortIsOpen(Integer port) {
		ServerSocket serverSocket = null;
		DatagramSocket dataSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			serverSocket.setReuseAddress(true);
			dataSocket = new DatagramSocket(port);
			dataSocket.setReuseAddress(true);
			return true;
		} catch (final IOException e) {
			return false;
		} finally {
			if (dataSocket != null) {
				dataSocket.close();
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (final IOException e) {
				}
			}
		}
	}

	private static Boolean checkIfIpIsLocal(String ip) {
		try {
			if (InetAddress.getByName(ip).isAnyLocalAddress() || InetAddress.getByName(ip).isLoopbackAddress()) {
				return true;
			}
			return NetworkInterface.getByInetAddress(InetAddress.getByName(ip)) != null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static Boolean isProperIpString(String ip) {
		String ipAddressPattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
		return ip.matches(ipAddressPattern);
	}

	public static String getLocatorURI(String ip, String port) {
		return ip + ":" + port;
	}

	public static String getIp(String locatorUri) {
		return locatorUri.split(":")[0];
	}

	public static String getPort(String locatorUri) {
		return locatorUri.split(":")[1];
	}
}
